package com.process.runner;


import com.core.system.domain.Apicode;
import com.system.service.ApicodeService;
import io.swagger.models.Operation;
import io.swagger.models.Path;
import liquibase.integration.spring.SpringLiquibase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import springfox.documentation.service.Documentation;
import springfox.documentation.spring.web.DocumentationCache;
import springfox.documentation.swagger2.mappers.ServiceModelToSwagger2Mapper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Component
@ConditionalOnBean(value = {SpringLiquibase.class})
public class ApiRunner implements ApplicationRunner {
    @Value("${spring.profiles.active:dev}")
    private String active;
    @Value("${spring.application.name}")
    private String appName;
    @Autowired
    private ApicodeService apicodeService;
    @Autowired
    private DocumentationCache documentationCache;

    @Autowired
    private ServiceModelToSwagger2Mapper mapper;

    /**
     * 定时任务入库
     */
    private void addApiList() {
        Map<String, Documentation> all = this.documentationCache.all();

        Map<String, Path> paths = new HashMap<String, Path>();
        List<Apicode> apicodeList = new ArrayList<>();
        Apicode apicode = null;
        for (Documentation documentation : all.values()) {
            String basePath = documentation.getBasePath();
            String substring1 = null;
            Map<String, Path> paths1 = this.mapper.mapDocumentation(documentation).getPaths();
            for (String key : paths1.keySet()) {
                if (key.contains("admin")|| key.contains("flowable")) {
                    Operation operations = paths1.get(key).getOperations().get(0);
                    apicode = new Apicode();
                    if (key.contains("{")) {
                        key = key.substring(0, key.indexOf("{"));
                    }
                    apicode.setApicode(key);
                    apicode.setApiName(operations.getSummary());
                    apicode.setRemark(operations.getSummary());
                    apicode.setModule(documentation.getGroupName());
                    apicodeList.add(apicode);
                }
            }
        }
        //接口定时入库
        if (!CollectionUtils.isEmpty(apicodeList)) {
            apicodeService.inertList(apicodeList, null);
        }
    }

    public void run(ApplicationArguments args) throws Exception {
        new Thread(() -> {
            if (!"test".equals(this.active))
                addApiList();
        }).start();
    }
}
